package com.itwxz.system.service.impl;

import com.itwxz.common.core.domain.R;
import com.itwxz.system.domain.dto.EchartsOrderDto;
import com.itwxz.system.enums.order.OrderType;
import com.itwxz.system.service.IWxzOrderHistoryService;
import com.itwxz.system.service.IWxzOrderService;
import com.itwxz.system.service.WxzEchartsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class WxzEchartsServiceImpl implements WxzEchartsService {
    private final IWxzOrderService orderService;
    private final IWxzOrderHistoryService orderHistoryService;

    @Override
    public R<EchartsOrderDto> orderStatistics() {
        // 获取当前订单统计数据
        List<Map<String, Object>> currentOrderRaw = orderService.orderStatistics();

        // 获取历史订单统计数据
        List<Map<String, Object>> historyOrderRaw = orderHistoryService.orderStatistics();


        // 转换为 echarts 饼图格式
        List<Map<String, Object>> currentOrderPie = convertToPieChartFormat(currentOrderRaw);
        List<Map<String, Object>> historyOrderPie = convertToPieChartFormat(historyOrderRaw);

        EchartsOrderDto dto = EchartsOrderDto.builder()
                .order(currentOrderPie)
                .orderHistory(historyOrderPie)
                .orderBuilding(orderService.getOrderCountByBuilding())
                .recent7DaysOrderCount(orderService.selectRecent7DaysOrderCount())
                .build();

        return R.ok(dto);
    }

    /**
     * 将原始统计数据转换为 echarts 饼图需要的格式 [{name: '软件', value: 10}, ...]
     */
    private List<Map<String, Object>> convertToPieChartFormat(List<Map<String, Object>> rawList) {
        // 临时存储 type -> count
        Map<Integer, Integer> typeCountMap = new HashMap<>();

        for (Map<String, Object> map : rawList) {
            Integer type = (Integer) map.get("type");
            Long count = (Long) map.get("order_count");
            typeCountMap.put(type, count.intValue());
        }

        // 构建最终结果
        List<Map<String, Object>> result = new ArrayList<>();
        for (OrderType type : OrderType.values()) {
            Map<String, Object> data = new HashMap<>();
            data.put("name", type.getDesc());
            data.put("value", typeCountMap.getOrDefault(type.getCode(), 0));
            result.add(data);
        }
        return result;
    }

}
